<template>
  <div class="cart-page">
    <front-header></front-header>
    
    <!-- 背景装饰 -->
    <div class="bg-decoration">
      <div class="circle circle-1"></div>
      <div class="circle circle-2"></div>
      <div class="circle circle-3"></div>
      <div class="leaf leaf-1"></div>
      <div class="leaf leaf-2"></div>
    </div>
    
    <div class="main-content">
      <!-- 购物车标题 -->
      <div class="page-header">
        <div class="header-left">
          <h2>我的购物车</h2>
          <div class="cart-count">共 {{ totalItems }} 件商品</div>
        </div>
        <div class="header-right">
          <el-button type="success" icon="el-icon-shopping-bag-1" @click="$router.push('/products')">继续购物</el-button>
        </div>
      </div>

      <!-- 购物车主体 -->
      <div class="cart-container" v-loading="loading">
        <!-- 空购物车提示 -->
        <el-empty v-if="!loading && cartItems.length === 0" description="购物车是空的">
          <div class="empty-description">
            <p>您的购物车还没有商品，快去选购吧！</p>
          </div>
          <el-button type="primary" @click="$router.push('/products')">去购物</el-button>
        </el-empty>

        <!-- 购物车列表 -->
        <div v-else class="cart-layout">
          <!-- 左侧商品列表 -->
          <div class="cart-items-section">
            <div class="cart-header">
              <el-checkbox v-model="allSelected" @change="handleSelectAll">全选</el-checkbox>
              <span class="header-title">商品信息</span>
            </div>
            
            <div class="cart-list">
              <div v-for="item in cartItems" :key="item.id" class="cart-item-card">
                <div class="item-select">
                  <el-checkbox v-model="item.selected" @change="handleItemSelect"></el-checkbox>
                </div>
                
                <div class="item-image">
                  <el-image :src="'api'+item.product.imageUrl" fit="cover" @click="$router.push(`/product/${item.product.id}`)">
                    <div slot="error" class="image-slot">
                      <i class="el-icon-picture-outline"></i>
                    </div>
                  </el-image>
                </div>
                
                <div class="item-info">
                  <div class="item-name">{{ item.product.name }}</div>
                  <div class="item-stock">库存: {{ item.product.stock }}</div>
                  
                  <div class="item-price-row">
                    <div class="item-price">
                      <span class="current-price">¥{{ item.product.isDiscount ? item.product.discountPrice : item.product.price }}</span>
                      <span class="original-price" v-if="item.product.isDiscount">¥{{ item.product.price }}</span>
                    </div>
                    
                    <div class="item-quantity">
                      <el-input-number v-model="item.quantity" :min="1" :max="item.product.stock" size="small"
                        @change="(value) => handleQuantityChange(item, value)"></el-input-number>
                    </div>
                  </div>
                  
                  <div class="item-actions">
                    <span class="item-subtotal">小计: <strong>¥{{ calculateSubtotal(item).toFixed(2) }}</strong></span>
                    <el-button type="text" class="delete-btn" @click="handleDelete(item)">删除</el-button>
                  </div>
                </div>
              </div>
            </div>
            
            <div class="cart-actions">
              <div class="actions-left">
                <el-checkbox v-model="allSelected" @change="handleSelectAll">全选</el-checkbox>
                <el-button type="text" class="delete-btn" @click="handleBatchDelete">删除选中商品</el-button>
              </div>
            </div>
          </div>
          
          <!-- 右侧结算区域 -->
          <div class="checkout-section">
            <div class="checkout-card">
              <div class="checkout-title">
                <i class="el-icon-shopping-cart-2"></i> 订单摘要
              </div>
              
              <div class="checkout-content">
                <div class="checkout-row">
                  <span>已选商品</span>
                  <span>{{ selectedCount }} 件</span>
                </div>
                
                <div class="checkout-row">
                  <span>商品总价</span>
                  <span class="price">¥{{ totalPrice.toFixed(2) }}</span>
                </div>
                
                <div class="checkout-divider"></div>
                
                <div class="checkout-row total">
                  <span>应付总额</span>
                  <span class="total-price">¥{{ totalPrice.toFixed(2) }}</span>
                </div>
                
                <!-- 收货地址选择区域 -->
                <div class="address-section" v-if="cartItems.some(item => item.selected)">
                  <div class="section-title">
                    <i class="el-icon-location"></i>
                    收货地址
                  </div>
                  
                  <el-select v-model="selectedAddressId" placeholder="请选择收货地址" class="address-select">
                    <el-option v-for="addr in addresses" :key="addr.id" :label="formatAddress(addr)" :value="addr.id">
                      <div class="address-option">
                        <div class="receiver-info">
                          <span class="receiver-name" v-if="addr.receiver">{{ addr.receiver }}</span>
                          <span class="phone">{{ addr.phone }}</span>
                          <el-tag v-if="addr.isDefault === 1" size="mini" type="success">默认</el-tag>
                        </div>
                        <div class="address-detail">{{ addr.address }}</div>
                      </div>
                    </el-option>
                  </el-select>
                  
                  <div class="address-actions">
                    <el-button type="text" icon="el-icon-plus" @click="$router.push('/user-center')">
                      添加新地址
                    </el-button>
                  </div>
                </div>
                
                <el-button type="primary" size="large" class="checkout-btn" 
                  :disabled="selectedCount === 0 || !selectedAddressId" 
                  @click="handleCheckout">
                  结算
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <front-footer></front-footer>
  </div>
</template>

<script>
import FrontHeader from '@/components/front/FrontHeader.vue'
import FrontFooter from '@/components/front/FrontFooter.vue'
import Request from '@/utils/request'

export default {
  name: 'Cart',
  components: {
    FrontHeader,
    FrontFooter
  },
  data() {
    return {
      userInfo: JSON.parse(localStorage.getItem('frontUser') || '{}'),
      loading: false,
      cartItems: [],
      allSelected: false,
      selectedAddressId: null,
      addresses: []
    }
  },
  computed: {
    totalItems() {
      return this.cartItems.length
    },
    selectedCount() {
      return this.cartItems.filter(item => item.selected).length
    },
    totalPrice() {
      return this.cartItems
        .filter(item => item.selected)
        .reduce((total, item) => {
          const price = item.product.isDiscount === 1 ? item.product.discountPrice : item.product.price
          return total + price * item.quantity
        }, 0)
    }
  },
 
  methods: {
    // 获取购物车数据
    async getCartItems() {
      this.loading = true
      try {
        const userId = this.userInfo.id
        const res = await Request.get(`/cart/user/${userId}`)
        if (res.code === '0') {
          this.cartItems = res.data ? res.data.map(item => ({
            ...item,
            selected: false
          })) : []
          // 如果购物车为空，确保显示空状态
          if (!res.data || res.data.length === 0) {
            this.cartItems = []
          }
        }
      } catch (error) {
        console.error('获取购物车失败:', error)
        this.$message.error('获取购物车失败')
      } finally {
        this.loading = false
      }
    },
    // 更新商品数量
    async handleQuantityChange(item, value) {
      const originalQuantity = item.quantity
      try {
        await Request.put(`/cart/${item.id}?quantity=${value}`)
        this.$message.success('更新成功')
      } catch (error) {
        console.error('更新数量失败:', error)
        this.$message.error('更新数量失败')
        // 恢复原数量
        item.quantity = originalQuantity
      }
    },
    // 删除
    async handleDelete(item) {
      try {
        await this.$confirm('确定要删除该商品吗？', '提示', {
          type: 'warning'
        })
         Request.delete(`/cart/${item.id}`).then(res=>{
          if(res.code === '0'){
            this.$message.success('删除成功')
            // 更新本地数据以立即反映删除操作
            const index = this.cartItems.findIndex(i => i.id === item.id)
            if (index !== -1) {
              this.cartItems.splice(index, 1)
            }
            // 如果已经没有商品，确保更新全选状态
            if (this.cartItems.length === 0) {
              this.allSelected = false
            }
          }
         })
       
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },
    // 批量删除
    async handleBatchDelete(isCheckout = false) {
      try {
        const selectedItems = this.cartItems.filter(item => item.selected)
        if (selectedItems.length === 0 && !isCheckout) {
          this.$message.warning('请选择要删除的商品')
          return
        }

        if (!isCheckout) {
          await this.$confirm('确定要删除选中的商品吗？', '提示', {
            type: 'warning'
          })
        }

        const ids = selectedItems.map(item => item.id).join(',')
        const res = await Request.delete(`/cart/batch?ids=${ids}`)
        if (res.code === '0') {
          if (!isCheckout) {
            this.$message.success('删除成功')
          }
          // 直接从本地列表中移除被删除的商品
          for (const item of selectedItems) {
            const index = this.cartItems.findIndex(i => i.id === item.id)
            if (index !== -1) {
              this.cartItems.splice(index, 1)
            }
          }
          // 如果没有商品了，重置全选状态
          if (this.cartItems.length === 0) {
            this.allSelected = false
          }
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },
    // 全选/取消全选
    handleSelectAll(val) {
      this.cartItems.forEach(item => {
        item.selected = val
      })
    },
    // 单个商品选择
    handleItemSelect() {
      this.allSelected = this.cartItems.every(item => item.selected)
    },
    // 结算
    async handleCheckout() {
      if (this.addresses.length === 0) {
        this.$message.warning('您还没有添加收货地址')
        this.$router.push('/user-center')
        return
      }
      
      if (!this.selectedAddressId) {
        this.$message.warning('请选择收货地址')
        return
      }

      try {
        const selectedItems = this.cartItems.filter(item => item.selected)
        const selectedAddress = this.addresses.find(addr => addr.id === this.selectedAddressId)
        
        // 为每个选中的商品创建单独的订单
        const orderPromises = selectedItems.map(item => {
          const orderData = {
            userId: this.userInfo.id,
            productId: item.product.id,
            quantity: item.quantity,
            price: item.product.isDiscount === 1 
              ? item.product.discountPrice 
              : item.product.price,
            totalPrice: this.calculateSubtotal(item),
            recvAddress: selectedAddress.address,
            recvPhone: selectedAddress.phone,
            recvName: selectedAddress.receiver,
            status: 0 // 待支付状态
          }
          return Request.post('/order', orderData)
        })

        const results = await Promise.all(orderPromises)
        const hasError = results.some(res => res.code !== '0')

        if (!hasError) {
          this.$message.success('下单成功')
          await this.handleBatchDelete(true)
          this.$router.push('/order')
        } else {
          throw new Error('部分订单创建失败')
        }
      } catch (error) {
        console.error('下单失败:', error)
        this.$message.error('下单失败')
      }
    },
    async getAddresses() {
      try {
          const userId = this.userInfo.id
        const res = await Request.get(`/address/user/${userId}`)
        if (res.code === '0') {
          this.addresses = res.data
          // 如果有默认地址，自动选中默认地址
          const defaultAddress = this.addresses.find(addr => addr.isDefault === 1)
          if (defaultAddress) {
            this.selectedAddressId = defaultAddress.id
          }
          // 如果没有默认地址但只有一个地址，自动选中
          else if (this.addresses.length === 1) {
            this.selectedAddressId = this.addresses[0].id
          }
        }
      } catch (error) {
        console.error('获取地址列表失败:', error)
        this.$message.error('获取地址列表失败')
      }
    },
    formatAddress(addr) {
      return `${addr.receiver ? addr.receiver + ' ' : ''}${addr.phone} ${addr.address}`
    },
    // 添加小计计算方法
    calculateSubtotal(item) {
      const price = item.product.isDiscount === 1 ? item.product.discountPrice : item.product.price
      return price * item.quantity
    }
  },
  created() {
    const userInfo = localStorage.getItem('frontUser')
    if(!userInfo){
      this.$message.warning('请先登录')
      this.$router.push('/login')
    }
    else{
      this.userInfo = JSON.parse(userInfo)
      this.getCartItems()
      this.getAddresses()
    }
  },
  mounted() {
 
  }
}
</script>

<style scoped>
/* 整体布局样式 */
.cart-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #fff8e1 0%, #fff3e0 100%);
  position: relative;
  overflow: hidden;
}

/* 背景装饰 */
.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
  pointer-events: none;
}

.circle {
  position: absolute;
  border-radius: 50%;
  background: linear-gradient(135deg, rgba(255, 152, 0, 0.1), rgba(255, 193, 7, 0.05));
}

.circle-1 {
  width: 600px;
  height: 600px;
  top: -200px;
  right: -100px;
}

.circle-2 {
  width: 400px;
  height: 400px;
  bottom: -100px;
  left: -100px;
}

.circle-3 {
  width: 300px;
  height: 300px;
  top: 40%;
  right: 10%;
  background: linear-gradient(135deg, rgba(255, 193, 7, 0.05), rgba(255, 152, 0, 0.08));
}

.leaf {
  position: absolute;
  background-color: rgba(255, 152, 0, 0.1);
  border-radius: 50% 0;
  transform: rotate(45deg);
}

.leaf-1 {
  width: 200px;
  height: 200px;
  bottom: 10%;
  right: 5%;
}

.leaf-2 {
  width: 150px;
  height: 150px;
  top: 20%;
  left: 5%;
  transform: rotate(-30deg);
}

.main-content {
  flex: 1;
  padding: 32px;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
  box-sizing: border-box;
  position: relative;
  z-index: 2;
}

/* 页面标题样式 */
.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-header h2 {
  font-size: 28px;
  font-weight: 600;
  color: #F57C00;
  margin: 0;
  position: relative;
}

.cart-count {
  color: #FF9800;
  font-size: 14px;
  font-weight: 500;
  background: rgba(255, 193, 7, 0.1);
  padding: 6px 16px;
  border-radius: 20px;
}

/* 新的购物车布局 */
.cart-container {
  min-height: 400px;
  position: relative;
}

.cart-layout {
  display: grid;
  grid-template-columns: 1fr 350px;
  gap: 24px;
}

/* 左侧商品列表区域 */
.cart-items-section {
  background: white;
  border-radius: 16px;
  border: 1px solid rgba(255, 193, 7, 0.1);
  overflow: hidden;
}

.cart-header {
  padding: 20px 24px;
  background: rgba(255, 193, 7, 0.05);
  border-bottom: 1px solid rgba(255, 193, 7, 0.1);
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-title {
  font-size: 16px;
  font-weight: 500;
  color: #FF9800;
}

.cart-list {
  padding: 16px;
}

.cart-item-card {
  display: flex;
  background: white;
  border-radius: 12px;
  border: 1px solid rgba(255, 193, 7, 0.1);
  padding: 16px;
  margin-bottom: 16px;
  transition: all 0.3s ease;
}

.cart-item-card:hover {
  box-shadow: 0 6px 16px rgba(255, 152, 0, 0.08);
  transform: translateY(-2px);
}

.item-select {
  display: flex;
  align-items: center;
  padding-right: 16px;
}

.item-image {
  width: 100px;
  height: 100px;
  margin-right: 20px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid rgba(255, 193, 7, 0.1);
}

.item-image :deep(.el-image) {
  width: 100%;
  height: 100%;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.item-image :deep(.el-image:hover) {
  transform: scale(1.05);
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.item-name {
  font-size: 16px;
  font-weight: 500;
  color: #F57C00;
  margin-bottom: 8px;
  cursor: pointer;
  transition: color 0.3s ease;
}

.item-name:hover {
  color: #FF9800;
}

.item-stock {
  font-size: 13px;
  color: #666;
  padding: 2px 8px;
  background: rgba(255, 193, 7, 0.05);
  border-radius: 4px;
  display: inline-block;
  margin-bottom: 12px;
}

.item-price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.item-price {
  display: flex;
  align-items: baseline;
  gap: 8px;
}

.current-price {
  font-size: 18px;
  font-weight: 600;
  color: #ff4757;
}

.original-price {
  font-size: 14px;
  color: #909399;
  text-decoration: line-through;
}

.item-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-subtotal {
  font-size: 15px;
  color: #606266;
}

.item-subtotal strong {
  font-size: 18px;
  color: #ff4757;
}

.cart-actions {
  padding: 16px 24px;
  background: rgba(255, 193, 7, 0.05);
  border-top: 1px solid rgba(255, 193, 7, 0.1);
}

.actions-left {
  display: flex;
  align-items: center;
  gap: 24px;
}

/* 右侧结算区域 */
.checkout-section {
  align-self: start;
}

.checkout-card {
  background: white;
  border-radius: 16px;
  border: 1px solid rgba(255, 193, 7, 0.1);
  overflow: hidden;
  position: sticky;
  top: 24px;
}

.checkout-title {
  padding: 20px 24px;
  background: rgba(255, 193, 7, 0.05);
  border-bottom: 1px solid rgba(255, 193, 7, 0.1);
  font-size: 18px;
  font-weight: 500;
  color: #F57C00;
  display: flex;
  align-items: center;
  gap: 8px;
}

.checkout-title i {
  color: #FF9800;
}

.checkout-content {
  padding: 24px;
}

.checkout-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
  font-size: 15px;
  color: #606266;
}

.checkout-row.total {
  font-size: 16px;
  font-weight: 500;
  color: #F57C00;
  margin-top: 8px;
  margin-bottom: 24px;
}

.checkout-row .price {
  color: #ff4757;
}

.checkout-row .total-price {
  font-size: 24px;
  font-weight: 600;
  color: #ff4757;
}

.checkout-divider {
  height: 1px;
  background: rgba(255, 193, 7, 0.1);
  margin: 16px 0;
}

.checkout-btn {
  width: 100%;
  height: 48px;
  margin-top: 24px;
  background: linear-gradient(135deg, #FF9800, #FFC107) !important;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  box-shadow: 0 4px 12px rgba(255, 152, 0, 0.2);
  transition: all 0.3s ease;
}

.checkout-btn:hover:not(:disabled),
.checkout-btn:focus:not(:disabled),
.checkout-btn:active:not(:disabled) {
  background: linear-gradient(135deg, #F57C00, #FFB300) !important;
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(255, 152, 0, 0.3);
}

/* 收货地址区域样式 */
.address-section {
  margin-top: 24px;
}

.section-title {
  font-size: 16px;
  color: #F57C00;
  font-weight: 500;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-title i {
  color: #FF9800;
}

.address-select {
  width: 100%;
  margin-bottom: 8px;
}

.address-select :deep(.el-input__inner) {
  border-color: rgba(255, 193, 7, 0.2);
  border-radius: 8px;
}

.address-select :deep(.el-input__inner:focus) {
  border-color: #FF9800;
  box-shadow: 0 0 0 2px rgba(255, 152, 0, 0.2);
}

.address-actions {
  text-align: right;
}

.address-option {
  padding: 8px 0;
}

.receiver-info {
  margin-bottom: 4px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.receiver-name {
  font-weight: 500;
  color: #F57C00;
}

.phone {
  color: #606266;
  font-size: 14px;
}

.address-detail {
  color: #666;
  font-size: 13px;
}

/* 数量输入框样式 */
:deep(.el-input-number) {
  width: 120px;
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-input-number .el-input__inner) {
  text-align: center;
  border: 1px solid rgba(255, 193, 7, 0.2);
  transition: all 0.3s ease;
}

:deep(.el-input-number .el-input__inner:hover) {
  border-color: #FF9800;
}

:deep(.el-input-number__increase:hover),
:deep(.el-input-number__decrease:hover) {
  color: #FF9800;
}

/* Checkbox样式优化 */
:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #FF9800;
  border-color: #FF9800;
  transition: all 0.3s ease;
}

:deep(.el-checkbox__inner:hover) {
  border-color: #FF9800;
}

/* 按钮样式 */
:deep(.el-button--text) {
  color: #FF9800;
}

:deep(.el-button--text:hover) {
  color: #F57C00;
}

/* 覆盖Element UI按钮默认样式 */
:deep(.el-button--primary) {
  background-color: #FF9800;
  border-color: #FF9800;
  color: white;
}

:deep(.el-button--primary:hover),
:deep(.el-button--primary:focus),
:deep(.el-button--primary:active),
:deep(.el-button--primary.is-active) {
  background-color: #F57C00;
  border-color: #F57C00;
  color: white;
}

:deep(.el-button--success) {
  background-color: #FF9800;
  border-color: #FF9800;
  color: white;
}

:deep(.el-button--success:hover),
:deep(.el-button--success:focus),
:deep(.el-button--success:active),
:deep(.el-button--success.is-active) {
  background-color: #F57C00;
  border-color: #F57C00;
  color: white;
}

.delete-btn {
  color: #909399;
  transition: all 0.3s ease;
  font-size: 14px;
}

.delete-btn:hover {
  color: #ff4757;
}

:deep(.el-tag--success) {
  background-color: rgba(255, 193, 7, 0.1);
  border-color: rgba(255, 193, 7, 0.2);
  color: #FF9800;
}

/* 空购物车样式 */
:deep(.el-empty) {
  padding: 60px 0;
}

.empty-description {
  margin-top: 16px;
  color: #666;
}

:deep(.el-empty .el-button) {
  margin-top: 20px;
  padding: 12px 30px;
  font-size: 15px;
  border-radius: 24px;
  background: linear-gradient(135deg, #FF9800, #FFC107) !important;
  border: none;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(255, 152, 0, 0.2);
}

:deep(.el-empty .el-button:hover),
:deep(.el-empty .el-button:focus),
:deep(.el-empty .el-button:active) {
  background: linear-gradient(135deg, #F57C00, #FFB300) !important;
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(255, 152, 0, 0.3);
}

/* 加载状态样式 */
:deep(.el-loading-mask) {
  background-color: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(4px);
}

/* 响应式调整 */
@media (max-width: 992px) {
  .cart-layout {
    grid-template-columns: 1fr;
  }

  .checkout-section {
    order: -1;
    margin-bottom: 24px;
  }

  .checkout-card {
    position: static;
  }
}

@media (max-width: 768px) {
  .main-content {
    padding: 16px;
  }

  .cart-item-card {
    flex-direction: column;
  }

  .item-select {
    align-self: flex-start;
    padding-right: 0;
    padding-bottom: 16px;
  }

  .item-image {
    width: 100%;
    height: 200px;
    margin-right: 0;
    margin-bottom: 16px;
  }

  .item-price-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .header-right {
    align-self: stretch;
  }

  .header-right .el-button {
    width: 100%;
  }
}
</style>